from flask import Flask, render_template, request
from flask_sockets import Sockets
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
import json
from werkzeug.routing import Rule
from flask_cors import CORS

app = Flask(__name__)
sockets = Sockets(app)
CORS(app, supports_credentials=True, resources=r'/*')
users = {}
queue = []
WEBSOCKET_DICT = {}
room_dict = {}

class Room:
    def __init__(self, player1, player2, ws1, ws2):
        self.player1 = player1
        self.player2 = player2
        self.ws1 = ws1
        self.ws2 = ws2
        self.board = [[0 for j in range(10)] for i in range(10)]
        
def check(board, color, row, col):
    line = 0
    for i in range(10):
        if board[row][i] == color:
            line += 1
            if line >= 5:
                return True
        else:
            line = 0
    line = 0
    for i in range(10):
        if board[i][col] == color:
            line += 1
            if line >= 5:
                return True
        else:
            line = 0
    line = 0
    i = row
    j = col
    while i > 0 and j > 0 :
        i -= 1
        j += 1
    while i < 10 and j < 10 :
        if board[i][j] == color:
            line += 1
            if line >= 5:
                return True
        else:
            line = 0
        i += 1
        j -= 1
    line = 0
    i = row
    j = col
    while i > 0 and j > 0 :
        i -= 1
        j -= 1
    while i < 10 and j < 10 :
        if board[i][j] == color:
            line += 1
            if line >= 5:
                return True
        else:
            line = 0
        i += 1
        j += 1
    return False

@sockets.route('/ws')
def game_socket(ws):
    #ws = request.environ.get('wsgi.websocket')
    while not ws.closed:
        msg = ws.receive()
        data = json.loads(msg)
        res_type = data["type"]
        print(data)
        # login = 0，登录请求
        if res_type == 0:
            user = data["username"]
            if user in users:
                ws.send(json.dumps({'type':0,'status':1}))
            else:
                users[user] = ws
                ws.send(json.dumps({'type':0,'status':0}))
            print("send")
        # start = 1，匹配请求
        elif res_type == 1:
            user = data["username"]
            if user not in queue and queue:
                try:
                    opponent = queue.pop(0)
                except:
                    queue.append(user)
                else:
                    ws2 = users[opponent]
                    room_dict[user] = Room(player1=user,player2=opponent,ws1=ws, ws2=ws2)
                    ws.send(json.dumps({'type':1,'status':0,'room':user,'usercolor':2,'opponentname':opponent}))
                    ws2.send(json.dumps({'type':1,'status':0,'room':user,'usercolor':1,'opponentname':user}))
                    print("send")
            else:
                queue.append(data["username"])
        # move = 2，下棋请求
        elif res_type == 2:
            row, col, color = data["row"], data["col"], data['color']
            room = room_dict[data["room"]]
            chessboard = room.board
            chessboard[row][col] = int(color)
            room.ws1.send(json.dumps({'type':2,'status':0,'color':color,'row':row,'col':col}))
            room.ws2.send(json.dumps({'type':2,'status':0,'color':color,'row':row,'col':col}))
            print("send")
            if(check(chessboard, color, row, col)):
                room.ws1.send(json.dumps({'type':3,'color':color}))
                room.ws2.send(json.dumps({'type':3,'color':color}))
                del users[room.player1]
                del users[room.player2]
                del room_dict[room.player1]
                del room
        # end = 3，停止请求
        elif res_type == 3:
            del users[data["username"]]

@app.route('/game')
def GOMOKU_game():
    return render_template("game.html")

if __name__ == "__main__":
    server = pywsgi.WSGIServer(('0.0.0.0', 8080), app, handler_class=WebSocketHandler)
    sockets.url_map.add(Rule('/ws', endpoint=game_socket, websocket=True))
    print('server start')
    server.serve_forever()